package ru.arriah.servicedesk.web.admin;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ru.arriah.common.bean.MessageBean;
import ru.arriah.common.web.UIController;
import ru.arriah.common.web.action.ActionMapping;
import ru.arriah.servicedesk.bean.EmployeeBean;
import ru.arriah.servicedesk.ejb.EmployeeManagerLocalHome;
import ru.arriah.servicedesk.ejb.EmployeeManagerLocalObject;
import ru.arriah.servicedesk.help.Utils;
import ru.arriah.servicedesk.web.commonaction.exception.LoginException;

public class AdminUI extends UIController {
   protected EmployeeManagerLocalHome employeeManagerHome;
   
   
   public AdminUI() {
      super();
      
   }
   
   public void init(ServletConfig config) throws ServletException {
      super.init(config);
      try {        
         employeeManagerHome =
            Utils.getEmployeeManagerHomeInterface();
         
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

   protected void prologue(
      ActionMapping actionMapping,
      HttpServletRequest request,
      HttpServletResponse response
   ) throws IOException, ServletException {

     request.getSession().setAttribute("alias", "adminui");
     
     Object userId = Utils.getUserId(request);

      if (
         userId == null && !actionMapping.getActionName().equals("login")
      ) {         
         throw new LoginException("ErrorMessage.relogin");
      }

      String uri = request.getRequestURI();
      String query = request.getQueryString();

      if (query != null) {
         uri += "?" + query;
      }

      String uriEncoded = URLEncoder.encode(uri, "UTF-8");
      request.setAttribute("uri", uri);
      request.setAttribute("uriEncoded", uriEncoded);
      
      request.setAttribute(
         "messagesList", 
         new ArrayList<MessageBean>()
      );
   }
   
   
   private void displayUserName(HttpServletRequest request) {
      try {
         int userId = Utils.getUserId(request);
         
         EmployeeManagerLocalObject employeeManager = 
            employeeManagerHome.create();
         
         EmployeeBean employeeBean = 
            employeeManager.selectEmployee(userId);
                  
         request.setAttribute("userName", employeeBean.getFormName());
         
         employeeManager.remove();
      } catch (Exception e) {
         e.printStackTrace();
      }     
   }

   
   protected void epilogue(
      ActionMapping actionMapping,
      HttpServletRequest request,
      HttpServletResponse response
   ) throws IOException, ServletException {
      
      this.displayUserName(request);
   }
}